﻿//
//  Monkey Manager
//  Copyright (C) 2010 Victor Tereschenko (aka sibvic)
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
//     
// ========================================================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;
using ManagerDB.SQLiteDB.Queries;

namespace ManagerDB
{
    partial class Database
    {
        public Database(string fileName)
        {
            mConnection = new SQLiteConnection(string.Format("Data Source={0};", fileName));
            mConnection.Open();
            mBuilder = new Builder(mConnection);
            mBuilder.CorrectTables();
            mTagController = new TabController(mConnection);
        }

        SQLiteConnection mConnection;
        TabController mTagController;
        Builder mBuilder;

        static string mInsertFileSQL = "INSERT INTO files(fileName, locationID) VALUES(@fileName, @locationID);";
        /// <summary>
        /// Adds a file into the DB.
        /// </summary>
        /// <param name="location">Location ID.</param>
        /// <param name="fileName">File name.</param>
        /// <returns>Stored file.</returns>
        public StoredFile AddFile(int location, string fileName)
        {
            SQLiteCommand command = new SQLiteCommand(mInsertFileSQL, mConnection);
            command.Parameters.Add(new SQLiteParameter("@fileName", fileName));
            command.Parameters.Add(new SQLiteParameter("@locationID", location));
            command.ExecuteNonQuery();

            SQLiteCommand selectCommand = new SQLiteCommand("SELECT rowid, fileName, year, day, month, title, description, count, lastPosition, locationID, TTH FROM files " +
                " WHERE locationID=@locationID AND fileName=@fileName", mConnection);
            selectCommand.Parameters.Add(new SQLiteParameter("@locationID", location));
            selectCommand.Parameters.Add(new SQLiteParameter("@fileName", fileName));
            SQLiteDataReader reader = selectCommand.ExecuteReader();
            if (!reader.Read())
                return null;

            StoredFile file = readFile(reader);
            reader.Close();
            return file;
        }

        private StoredFile readFile(SQLiteDataReader reader)
        {
            StoredFile file = new StoredFile();
            var fileInfo = new FileDescription();
            fileInfo.FileName = (string)reader["fileName"];
            fileInfo.Count = reader["count"] == DBNull.Value ? 0.0 : (float)reader["count"];
            fileInfo.LastPosition = reader["lastPosition"] == DBNull.Value ? 0.0 : (float)reader["lastPosition"];
            fileInfo.LocationID = (long)reader["locationID"];
            fileInfo.ID.TTH = reader["TTH"] == DBNull.Value ? "" : (string)reader["TTH"];
            file.ID = (long)reader["rowid"];
            file.Year = reader["year"] == DBNull.Value ? 0 : (long)reader["year"];
            file.Day = reader["day"] == DBNull.Value ? 0 : (long)reader["day"];
            file.Month = reader["month"] == DBNull.Value ? 0 : (long)reader["month"];
            file.Title = reader["title"] == DBNull.Value ? "" : (string)reader["title"];
            if (file.Title == "")
                file.Title = fileInfo.FileName;
            file.Description = reader["description"] == DBNull.Value ? "" : (string)reader["description"];
            file.Tags = mTagController.GetFileTags(file.ID);
            file.Files.Add(fileInfo);
            return file;
        }

        /// <summary>
        /// Deletes files
        /// </summary>
        /// <param name="fileID">File ID.</param>
        public void DeleteFile(long fileID)
        {
            SQLiteCommand command = new SQLiteCommand("DELETE FROM files WHERE rowid=@id", mConnection);
            command.Parameters.Add(new SQLiteParameter("@id", fileID));
            command.ExecuteNonQuery();
        }

        #region IDatabase interface
        public void Update(StoredFile file)
        {
            SQLiteCommand command = new SQLiteCommand(mConnection);
            StringBuilder sb = new StringBuilder();
            sb.Append("UPDATE files SET ");

            sb.Append("fileName=@fileName, ");
            command.Parameters.Add(new SQLiteParameter("@fileName", file.File.FileName));

            sb.Append("day=@day, ");
            command.Parameters.Add(new SQLiteParameter("@day", file.Day));

            sb.Append("month=@month, ");
            command.Parameters.Add(new SQLiteParameter("@month", file.Month));
        
            sb.Append("year=@year, ");
            command.Parameters.Add(new SQLiteParameter("@year", file.Year));

            sb.Append("title=@title, ");
            command.Parameters.Add(new SQLiteParameter("@title", file.Title));

            sb.Append("description=@description, ");
            command.Parameters.Add(new SQLiteParameter("@description", file.Description));

            sb.Append("count=@count, ");
            command.Parameters.Add(new SQLiteParameter("@count", file.File.Count));

            sb.Append("lastPosition=@lastPosition, ");
            command.Parameters.Add(new SQLiteParameter("@lastPosition", file.File.LastPosition));

            sb.Append("TTH=@tth ");
            command.Parameters.Add(new SQLiteParameter("@tth", file.File.ID.TTH));

            sb.Append("WHERE rowid=@id");
            command.Parameters.Add(new SQLiteParameter("@id", file.ID));

            command.CommandText = sb.ToString();
            command.ExecuteNonQuery();

            List<string> currentTags = mTagController.GetFileTags(file.ID);
            List<string> tagsToAdd = new List<string>();
            foreach (string tag in file.Tags)
            {
                if (currentTags.Contains(tag))
                {
                    // already have it
                    currentTags.Remove(tag);
                    continue;
                }

                // add new
                tagsToAdd.Add(tag);
            }

            // remove tags
            foreach (string tag in currentTags)
            {
                mBuilder.removeFileTag(file.ID, tag);
            }

            // add new tags
            foreach (string tag in tagsToAdd)
            {
                mBuilder.addFileTag(file.ID, tag);
            }
        }
        
        public StoredFile Find(string tth, long size)
        {
            var filter = new Filter();
            filter.TTH = tth;
            var files = Find(filter);
            if (files.Length == 0)
                return null;

            return files[0];
        }

        public StoredFile[] Find(Filter filter)
        {
            List<StoredFile> files = new List<StoredFile>();
            var command = SelectQueryBuilder.Create(mTagController, mConnection, filter);
            if (command == null)
                return files.ToArray();
            var reader = command.ExecuteReader();
            while (reader.Read())
            {
                StoredFile file = readFile(reader);
                files.Add(file);
            }
            reader.Close();

            return files.ToArray();
        }
        #endregion
    }
}
